package com.gitee.zhuyunlong2018.mybatisplusrelations.handler;

import com.gitee.zhuyunlong2018.mybatisplusrelations.context.IContext;
import com.gitee.zhuyunlong2018.mybatisplusrelations.func.IGetter;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.groupingBy;

public class ListBindManyHandler<T, R> extends ListHandler<T, R> {

    public ListBindManyHandler(IContext<T> context, IGetter<T, ?> propertyGetter) {
        super(context, propertyGetter);
    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    protected void buildRelation() {
        if (foreignEntityList == null || foreignEntityList.isEmpty()) {
            list.forEach(e -> cache.getRelationEntitySetter()
                    .accept(e, Collections.emptyList()));
            return;
        }
        HashMap collect = (HashMap) foreignEntityList
                .stream()
                .collect(groupingBy(cache.getForeignPropertyGetter()));
        list.forEach(e -> {
            List<R> subList = (List<R>) collect.get(cache.getLocalPropertyGetter().apply(e));
            if (subList == null || subList.isEmpty()) {
                cache.getRelationEntitySetter()
                        .accept(e, Collections.emptyList());
                return;
            }
            if (streamStatus) {
                Stream<R> stream = getForeignStream(subList);
                cache.getRelationEntitySetter()
                        .accept(e, stream.collect(Collectors.toList()));
            } else {
                cache.getRelationEntitySetter()
                        .accept(e, subList);
            }
        });
    }

}
